import { Controller, Get, Param, UseGuards, Req, UnauthorizedException, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import type { Request } from 'express';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  // 检查用户是否为管理员
  private checkAdminRole(user: any): void {
    if (user.role !== 'admin') {
      throw new UnauthorizedException('权限不足，需要管理员权限');
    }
  }

  @Get()
  @UseGuards(JwtAuthGuard)
  async findAll(@Req() req: Request) {
    this.checkAdminRole(req.user);
    return this.usersService.findAll();
  }

  @Get(':id')
  @UseGuards(JwtAuthGuard)
  async findOne(@Param('id') id: string, @Req() req: Request) {
    this.checkAdminRole(req.user);
    return this.usersService.findById(parseInt(id));
  }

  @Delete(':id')
  @UseGuards(JwtAuthGuard)
  async remove(@Param('id') id: string, @Req() req: Request) {
    this.checkAdminRole(req.user);
    await this.usersService.remove(parseInt(id));
  }
}